//index.js
//获取应用实例
const app = getApp()
var page = 1;
var merchant_list = [];
let loadingMore = false;
let loadedEnd = false;
Page({
  data: {
    userInfo: {},
    user_id:'',
    merchant:[],
    slide:[]
  },
  //事件处理函数
  onLoad:function(){
    wx.startPullDownRefresh();
    var value = wx.getStorageSync('user_id'); 
    if(value){
      this.getHomeList(page);
    }else{
      app.login()
      .then(app.doLogin)
      .then(app.checkAuth('scope.userInfo'))
      .then(app.getUserInfo)
      .then(this.getHomeList(page))
      .then(app.setUserData).catch(app.toLoad)
    }

  },
  onShow: function () {

  },
  getHomeList: function (page) {
    let that = this;
    wx.showToast({
      title: "数据加载中",
      icon: "loading"
    });
    return new Promise((resolve,reject)=>{
      console.log(page)
      wx.request({
        url: 'https://rtutrip.aihuodong.top/index/index/get_homepage_data',
        data: {
          page:page
        },
        success(res) {
          console.log(res.data.data);
          if (res.data.data.merchant.length == 0) {
            loadedEnd = true;
            wx.showToast({
              title: "已经到底啦",
              icon: "success"
            });
          }
          for (var i = 0; i < res.data.data.merchant.length; i++) {
            merchant_list.push(res.data.data.merchant[i]);
          }
          that.setData({
            merchant: merchant_list,
            slide: res.data.data.slider
          })
          resolve(res);
          wx.stopPullDownRefresh();
        }
      })
    })
  },
  onReachBottom() {
    if (loadingMore || loadedEnd) return false;
    loadingMore = true;
    wx.showToast({
      title: "数据加载中",
      icon: "loading"
    });
    page += 1;
    this.getHomeList(page);
    loadingMore = false;
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  makeCall:function(e){
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone
    })
  },
  onShareAppMessage: function (e) {
    return {
      title: '塞浦路斯土耳其免费信息平台',
      path: '/pages/merchant/merchant'
    }
  }
})
